<template>
  <div class="line-chart-container">
    <div ref="lineChart" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import moment from 'moment'; // 使用 moment.js 来处理日期

export default {
  name: "SalesLineChart",
  data() {
    return {
      chartInstance: null,
      option: {
        title: {
          text: `${moment().year()}年销售额`,
          left: 'center',
          textStyle: {
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '5%',  // 留出足够的边距
          right: '15%',
          top: '15%',   // 为标题和图例留出空间
          bottom: '15%',
          containLabel: true  // 保证标签也在布局内
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['Q1', 'Q2', 'Q3', 'Q4']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [{
          name: '销售额',
          type: 'line',
          data: [120000, 200000, 0, 0],
          markLine: {
            data: [{type: 'average', name: '平均值'}]
          }
        }]
      }

    };
  },
  mounted() {
    this.chartInstance = echarts.init(this.$refs.lineChart);
    this.chartInstance.setOption(this.option);
    window.addEventListener('resize', this.resizeChart);
  },
  methods: {
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    }
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    window.removeEventListener('resize', this.resizeChart);
  }
};
</script>

<style scoped>
.line-chart-container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center; 
}
</style>
